import XCookie from './XCookie'
import store from '../store/index'
import '../../static/js/geolocation.min.js'
import Vue from 'vue';
import XWxConfig from '../x/XWxConfig'
//用戶地理位置 更新时间间隔 -- 1小时
let userLocationUpdateTime = 1000 * 60 * 60 * 1;

//回調函數中需要用到
let that
let txLocationed = false;
let wxLocationed = false;
export default {
    /**
     * 刷新用户地理位置 by QQ lab
     */
    refreshUserLocationByQQLbs() {
        /*存在用户信息，就需要去判断是否更新，不存在要去定位*/
        that = this;
        if (this.isExistStoreLocation()) {
            if (this.isNeedUpdateUserLocation()) {
                if (Vue.prototype.v_is_weixin) {
                    that.wxLocation()
                } else {
                    that.tenXunLocation()
                }
            }
        } else {
            this.userGetHeSelfLocation()
        }
    },
    getLocationDiscount(obj) {
        that = this;
        let userLocation, storeDiscount;
        if (this.isNeedUpdateUserLocation()) {
            this.userGetHeSelfLocation();
        }
        return new Promise((resolve, reject) => {
            userLocation = this.getUserLocation();
            if (userLocation) {
                let tempDiscount = '';
                tempDiscount = parseInt(this.countDistance(userLocation.latitude, userLocation.longitude, obj.latitude, obj.longitude));
                storeDiscount = tempDiscount > 1000 ? parseInt(tempDiscount / 1000) + 'km' : parseInt(tempDiscount) + 'm';
                store.commit('currentUserStoreDiscount');
                resolve(storeDiscount);
            }
        })
    },
    tenXunLocation() {
        XCookie.doAlert("调用 qq lbs获取地理位置信息");
        let geolocation = new qq.maps.Geolocation(Vue.prototype.qqMapsKey, Vue.prototype.qqMapsAppName);
        //获取精确定位信息
        geolocation.getLocation(this.notifyPosition, this.notifyErr, {
            timeout: 10000,
            failTipFlag: true
        });
    },
    userGetHeSelfLocation() {
        that = this;
        if (Vue.prototype.v_is_weixin) {
            that.wxLocation()
        } else {
            that.tenXunLocation()
        }
        // let geolocation = new qq.maps.Geolocation(Vue.prototype.qqMapsKey, Vue.prototype.qqMapsAppName);
        // //获取精确定位信息
        // geolocation.getLocation(this.notifyPosition, this.notifyErr, {
        //     timeout: 10000,
        //     failTipFlag: true,
        // });
    },
    //QQ lab 回调通知位置信息
    notifyPosition(position) {
        txLocationed = true;
        if (position && JSON.stringify(position) && position.module == 'geolocation') { //定位成功,防止其他应用也会向该页面post信息，需判断module是否为'geolocation'
            //無論同意取消都可以獲得定位信息
            console.log('tx定位成功', position.lat, position.lng)
            that.updateUserLocation(position.lng, position.lat)  //這裏這能用that!!
        }
    },
    //QQ lab 回调通知错误信息
    //用户取消授权或者定位失败
    notifyErr() {
        that = this;
        if (!wxLocationed) {
            that.wxLocation();
        }
        console.log("tx定位失败！");
        return false;
    },
    //是否存在店铺地理位置信息
    isExistStoreLocation() {
        let currentStore = store.getters.currentStoreFn
        return !!currentStore && !!(Object.keys(currentStore).includes('longitude')) && !!(Object.keys(currentStore).includes('latitude'));
    },
    //获得铺地理位置信息
    getStoreLocation() {
        if (this.isExistStoreLocation()) {
            let currentStore = store.getters.currentStoreFn
            return {
                longitude: currentStore.longitude,
                latitude: currentStore.latitude
            }
        }
        return null
    },
    /**
     * 是否需要更新用戶地理位置信息数据
     */
    isNeedUpdateUserLocation() {
        let needUpdateUserLocation = !this.isExistUserLocation()
        let userLocationCache = this.getUserLocation()
        if (!needUpdateUserLocation && userLocationCache) {
            //判断是否超过更新时间
            needUpdateUserLocation = Date.parse(new Date()) - userLocationCache.refreshTime > userLocationUpdateTime
        }
        return needUpdateUserLocation
    },
    /**
     *  更新用戶地理位置信息
     */
    updateUserLocation(longitude, latitude) {
        let userLocationCache = {
            longitude: longitude,
            latitude: latitude,
            refreshTime: Date.parse(new Date())
        };
        if (userLocationCache) {
            store.commit('updateCurrentUser', userLocationCache);
            store.commit('updateCurrentThird', userLocationCache);
        }
        window.localStorage.setItem(Vue.prototype.userLocationKey, window.encodeURIComponent(JSON.stringify(userLocationCache)))
        store.commit('currentUserStoreDiscount');
    },
    /**
     *  是否存在用戶地理位置信息
     */
    isExistUserLocation() {
        let userLocation = this.getUserLocation();
        return (!!userLocation && userLocation != null && userLocation.longitude != null && userLocation.latitude != null)
    },
    /**
     *  獲得用戶地理位置信息
     */
    getUserLocation() {
        let userLocationCacheStr = window.localStorage.getItem(Vue.prototype.userLocationKey)
        return JSON.parse(window.decodeURIComponent(userLocationCacheStr))
    },
    //是否超出距离
    isOutDistance(limitKm) {
        if (!this.isExistStoreLocation()) {
            return false
        }
        if (!this.isExistUserLocation()) {
            return true
        }
        let userLocation = this.getUserLocation()
        let storeLocation = this.getStoreLocation()
        let distance = countDistance(userLocation.latitude, userLocation.longitude, storeLocation.latitude, storeLocation.longitude);
        XCookie.doAlert("userLocation  : " + JSON.stringify(userLocation))
        XCookie.doAlert("storeLocation  : " + JSON.stringify(storeLocation))
        XCookie.doAlert(distance + "===" + limitKm);
        return distance > limitKm
    },
    //计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
    countDistance(lat1, lng1, lat2, lng2) {
        var radLat1 = Rad(lat1);
        var radLat2 = Rad(lat2);
        var a = radLat1 - radLat2;
        var b = Rad(lng1) - Rad(lng2);
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
            Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137 * 1000;// EARTH_RADIUS;
        s = Math.round(s * 10000) / 10000; //输出为米
        //s=s.toFixed(4);
        return s;
    },
    wxLocation() {
        that = this;
        wxLocationed = true;
        let wxConfig = XWxConfig.getConfig();
        if (wxConfig) {
            wxConfig.jsApiList = ['getLocation'];
            wx.config(wxConfig);
            wx.ready(() => {
                wx.getLocation({
                    type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                    success: function (res) {
                        var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                        var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                        var speed = res.speed; // 速度，以米/每秒计
                        var accuracy = res.accuracy; // 位置精度
                        console.log('wx定位成功', latitude, longitude)
                        that.updateUserLocation(longitude, latitude)
                    },
                    fail(res) {
                        if (!txLocationed) {
                            that.tenXunLocation();
                        }
                        console.log('fail', res)
                    }
                })
            });
            wx.error(function (res) {
                console.log("wx验证失败！")
            });
        }else{
            that.tenXunLocation();
        }
    }
}

//进行经纬度转换为距离的计算

function Rad(d) {
    return d * Math.PI / 180.0;//经纬度转换成三角函数中度分表形式。
}

//计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
function countDistance(lat1, lng1, lat2, lng2) {
    var radLat1 = Rad(lat1);
    var radLat2 = Rad(lat2);
    var a = radLat1 - radLat2;
    var b = Rad(lng1) - Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137;// EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000; //输出为公里
    //s=s.toFixed(4);
    return s;
}

